from django.shortcuts import render
from rest_framework import viewsets, status, permissions
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework_simplejwt.tokens import RefreshToken
from django.contrib.auth import authenticate, login, logout
from .models import User, Supplier, DeliveryStaff
# 在文件顶部导入新的序列化器
from .serializers import (
    UserSerializer, SupplierSerializer, DeliveryStaffSerializer,
    LoginSerializer, RegisterSerializer, ChangePasswordSerializer # 确保 ChangePasswordSerializer 已导入
)
from .permissions import (
    IsAdmin, PurchaserPermission, SalesmanPermission, DeliverymanPermission, CustomerPermission,DeliveryAdminPermission
)
from django.contrib.auth import authenticate
from django.http import JsonResponse
from django.core.exceptions import ObjectDoesNotExist

# Create your views here.

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    permission_classes = [permissions.IsAuthenticated]

    def get_permissions(self):
        print(f"Action requested: {self.action}")
        print(f"User authenticated: {self.request.user.is_authenticated}")
        print(f"User role: {self.request.user.role if self.request.user.is_authenticated else 'Not authenticated'}")
        
        if self.action in ['login', 'register', 'change_password']: # 添加 'change_password' 到允许列表
            return [permissions.AllowAny()] # 或者根据您的需求设置为 IsAuthenticated
        elif self.action in ['list', 'destroy', 'update_user_role', 'get_users']:
            return [IsAdmin()]
        return [permissions.IsAuthenticated()]

    @action(detail=False, methods=['post'])
    def login(self, request):
        serializer = LoginSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        username = serializer.validated_data['username']
        password = serializer.validated_data['password']

        print(f"Login attempt - username: {username}")

        # 预定义角色的用户名和密码
        predefined_users = {
            'admin': ('admin123', 'admin'),
            'purchaser': ('purchaser123', 'purchaser'),
            'salesman': ('salesman123', 'salesman'),
            'deliveryman': ('deliveryman123', 'deliveryman')
        }

        try:
            user = User.objects.get(username=username)
            print(f"User found: {user.username}, role: {user.role}")
        except ObjectDoesNotExist:
            print(f"User not found, checking predefined users")
            if username in predefined_users and password == predefined_users[username][0]:
                user = User.objects.create_user(username=username, password=password)
                user.role = predefined_users[username][1]  # 使用元组中的第二个元素作为角色
                user.save()
                print(f"Created predefined user: {username} with role: {user.role}")
            else:
                print(f"Not a predefined user")
                return Response(
                    {'detail': '用户名或密码错误'},
                    status=status.HTTP_401_UNAUTHORIZED
                )

        if user.check_password(password):
            print(f"Password check passed")  # 添加调试日志
            refresh = RefreshToken.for_user(user)
            # 确保返回的用户信息包含角色
            user_info = UserSerializer(user).data
            user_info['role'] = user.role
            return Response({
                'user': user_info,
                'refresh': str(refresh),
                'access': str(refresh.access_token),
            })
        print(f"Password check failed")  # 添加调试日志
        return Response(
            {'detail': '用户名或密码错误'},
            status=status.HTTP_401_UNAUTHORIZED
        )

    @action(detail=False, methods=['put'], url_path='me/update') # 修改 url_path
    def update_profile(self, request):
        user = request.user
        serializer = UserSerializer(user, data=request.data, partial=True)
        if serializer.is_valid():
            # 保存更新后的用户信息
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    @action(detail=False, methods=['post'])
    def register(self, request):
        serializer = RegisterSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.save()
        refresh = RefreshToken.for_user(user)
        return Response({
            'user': UserSerializer(user).data,
            'refresh': str(refresh),
            'access': str(refresh.access_token),
        }, status=status.HTTP_201_CREATED)

    @action(detail=False, methods=['post'])
    def logout(self, request):
        try:
            refresh_token = request.data["refresh"]
            token = RefreshToken(refresh_token)
            token.blacklist()
            return Response({'detail': '已成功退出登录'})
        except Exception:
            return Response({'detail': '退出登录失败'}, status=status.HTTP_400_BAD_REQUEST)

    @action(detail=False, methods=['get'])
    def profile(self, request):
        return Response(UserSerializer(request.user).data)

    @action(detail=False, methods=['get'])
    def permissions(self, request):
        return Response({
            'is_admin': request.user.role == 'admin',
            'can_purchase': request.user.has_purchase_permission(),
            'can_sales': request.user.has_sales_permission(),
            'can_delivery': request.user.has_delivery_permission(),
            'is_customer': request.user.has_customer_permission(),
        })

    @action(detail=False, methods=['get'], url_path='all') # 建议为获取所有用户列表的接口指定一个更明确的url_path
    def get_users(self, request):
        """获取所有用户列表"""
        print(f"Get users requested by: {request.user.username if request.user.is_authenticated else 'Anonymous'}")
        print(f"User authenticated: {request.user.is_authenticated}")
        print(f"User role: {request.user.role if request.user.is_authenticated else 'Not authenticated'}")
        print(f"Request headers: {request.headers}")
        
        users = User.objects.all()
        print(f"Total users found: {users.count()}")
        print(f"Users data: {list(users.values('id', 'username', 'role', 'email', 'phone'))}")
        
        serializer = UserSerializer(users, many=True)
        print(f"Serialized data: {serializer.data}")
        
        return Response(serializer.data)

    @action(detail=True, methods=['put'], url_path='update-role') # 建议为更新用户角色的接口指定一个更明确的url_path
    def update_user_role(self, request, pk=None):
        """更新用户角色"""
        try:
            user = User.objects.get(pk=pk)
            new_role = request.data.get('role')
            
            if new_role not in [role[0] for role in User.ROLE_CHOICES]:
                return Response(
                    {'detail': '无效的角色类型'},
                    status=status.HTTP_400_BAD_REQUEST
                )
            
            user.role = new_role
            user.save()
            
            serializer = UserSerializer(user)
            return Response(serializer.data)
        except User.DoesNotExist:
            return Response(
                {'detail': '用户不存在'},
                status=status.HTTP_404_NOT_FOUND
            )

    # 将 change_password action 移到这里，作为 UserViewSet 类的方法
    @action(detail=False, methods=['post'], url_path='change-password')
    def change_password(self, request):
        user = request.user
        serializer = ChangePasswordSerializer(data=request.data, context={'request': request})
        if serializer.is_valid():
            serializer.save() # serializer 内部处理旧密码验证和新密码设置
            return Response({'detail': '密码修改成功'}, status=status.HTTP_200_OK)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class SupplierViewSet(viewsets.ModelViewSet):
    queryset = Supplier.objects.all()
    serializer_class = SupplierSerializer
    permission_classes = [permissions.IsAuthenticated]

class DeliveryStaffViewSet(viewsets.ModelViewSet):
    queryset = DeliveryStaff.objects.all()
    serializer_class = DeliveryStaffSerializer
    permission_classes = [DeliverymanPermission | DeliveryAdminPermission | IsAdmin]

@action(detail=False, methods=['post'])
def login(self, request):
    serializer = LoginSerializer(data=request.data)
    serializer.is_valid(raise_exception=True)
    username = serializer.validated_data['username']
    password = serializer.validated_data['password']

    predefined_users = {
        'admin': ('admin123', 'admin'),
        'purchaser': ('purchaser123', 'purchaser'),
        'salesman': ('salesman123', 'salesman'),
        'deliveryman': ('deliveryman123', 'deliveryman'),
    }

    try:
        user = User.objects.get(username=username)
        if not user.check_password(password):
            return Response({'detail': '用户名或密码错误'}, status=status.HTTP_401_UNAUTHORIZED)
    except ObjectDoesNotExist:
        # 判断是否是预设角色
        if username in predefined_users and password == predefined_users[username][0]:
            user = User.objects.create_user(username=username, password=password)
            user.role = predefined_users[username][1]
            user.save()
        else:
            # 普通客户注册
            user = User.objects.create_user(username=username, password=password)
            user.role = 'customer'
            user.save()

    # 成功登录，发放 token
    refresh = RefreshToken.for_user(user)
    user_info = UserSerializer(user).data
    user_info['role'] = user.role

    return Response({
        'user': user_info,
        'refresh': str(refresh),
        'access': str(refresh.access_token),
    })
